package cc.ufinity.networkdiagnose.widget;

import android.app.Activity;
import android.graphics.Color;
import android.net.ConnectivityManager;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiInfo;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.ScrollView;
import android.widget.TextView;
import cc.ufinity.networkdiagnose.app.GlobalApp;
import cc.ufinity.networkdiagnose.manager.FTPConfig;
import cc.ufinity.networkdiagnose.manager.MessageWhat;
import cc.ufinity.networkdiagnose.manager.NetworkManager;
import cc.ufinity.networkdiagnose.manager.Task;
import cc.ufinity.networkdiagnose.manager.WlanManager;
import cc.ufinity.networkdiagnose.util.StringUtils;
import cc.ufinity.networkdiagnose.view.R;

public class RoamTestWidget extends GeneralTestWidget {
    private WlanManager wlanManager;
    private NetworkManager nm;
    private Activity ctx;
    private Handler handler;
    private Button btnback;
    private Button btnRetest;
    private Button btnStart;
    private LinearLayout roamLayout;
    private ScrollView roamSv;
    private boolean processing;
    private EditText ipEt;
    private EditText frequencyEt;
    private EditText byteEt;
    private int current;
    private int successTimes = 0;
    private int roamTimes = 0;
    private int frequency;
    private Task task;
    private String fileName;
    private String currentMac = "";
    private String orignMac = "";
    private String pingMac = "";
    private String priorMac = "";
    private boolean isRoamSucceed = false;
    private ProgressBar pb;
    private LinearLayout llPb;
    private TextView tvTesting;
    
    private boolean isOver = true;
    private boolean isPingSuccess = false;
    
    public RoamTestWidget(Activity context) {
        super(context);
        this.ctx = context;
        isOver = true;
        wlanManager = new WlanManager(ctx);
        inflate(context, R.layout.roam_ping, this);
        btnback = (Button) this.findViewById(R.id.roam_test_btnback);
   //     btnRetest = (Button) this.findViewById(R.id.btn_roam_retest);
        btnStart = (Button) this.findViewById(R.id.btn_roam_start);
        roamLayout = (LinearLayout) this.findViewById(R.id.roam_test_detail);
        roamSv = (ScrollView) this.findViewById(R.id.roam_test_ScrView);
        ipEt = (EditText) this.findViewById(R.id.roamEditText);
        frequencyEt = (EditText) this.findViewById(R.id.roamFrequencyEditText);
        pb = (ProgressBar)this.findViewById(R.id.roma_ping_progress);
        llPb = (LinearLayout)this.findViewById(R.id.linearlaout_roam_ping);
        tvTesting = (TextView)this.findViewById(R.id.roma_ping_test);
        byteEt = (EditText) this.findViewById(R.id.roambyteEditText);
        handler = new Handler() {
            public void handleMessage(Message msg) {
                switch (msg.what) {
                case MessageWhat.WIFI_RECEIVE_LIST:
                    showWifiListDialog(ctx, wlanManager, handler);
                    dismissMessageDialog();
                    wlanManager.stopScan();
                    break;
                case MessageWhat.WIFI_SUCESS_CONNECTED:
                	String ip = wlanManager.getIpAddress()==null?"":wlanManager.getIpAddress();
                	if(ip.length()>4 && ip.lastIndexOf(".")>0)
                    	ip = ip.substring(0,ip.lastIndexOf(".")+1);
                    ipEt.setText(ip);
                    ipEt.setSelection(ip.length());
                    frequencyEt.setText("100");
                    byteEt.setText("100");
                    dismissMessageDialog();
                    break;
                case MessageWhat.WIFI_SELECTED:
                    enableNetWork(selectedScanResult);
                    break;
                case MessageWhat.FTP_ACCOUNT_INVALID:
                    dismissMessageDialog();
                    showMessage(ctx, "无法获取FTP账号，请检查FTP配置.");
                    break;
                case MessageWhat.FTP_UPLOAD_TASK_DONE:
                    dismissMessageDialog();
                    showMessage(ctx, "上传成功.");
                    break;
                case MessageWhat.FTP_UPLOAD_FAILED:
                    dismissMessageDialog();
                    showMessage(ctx, "上传失败，请检查FTP配置是否正确.");
                    break;
                case MessageWhat.FTP_LOGIN_FAILED:
                    dismissMessageDialog();
                    showMessage(ctx, "FTP登录失败，请检查FTP配置是否正确.");
                    break;
                default:
                    update(msg.what);
                }
            }
        };
        btnback.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
            	switch(GlobalApp.nowNetType) {
				case 1:
					backToTestWidget_Wlan(ctx);
					break;
				case 2:
					backToTestWidget_TD(ctx);
					break;
				case 3:
					backToTestWidget_GSM(ctx);
					break;
				default:
					break;
				}
            }
        });
       /* btnRetest.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                // RoamTestWidget ww = new RoamTestWidget(ctx);
                // ctx.setContentView(ww);
                if (null != fileName) {
               //     new UploadResultTask().execute();           //////////////////////////////////
                } else {
                    showMessage(ctx, "文件已上传或未进行测试.");
                }
            }
        });*/
        btnStart.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
            	if(isOver) {
            		roamLayout.removeAllViews();
                    start();
            	} else {
            		showMessage(getContext(), "正在漫游测试，请稍后再试");
            	}
            }
        });
        wlanManager.setHandler(handler);
        nm = new NetworkManager();
        nm.setHandler(handler);
        task = new Task();
        scanWifi();
    }

    public void update(int what) {
        //this.setDialogProgress(current);
    	pb.setProgress(current);
        TextView tv = null;
        StringBuffer s = null;
        switch (what) {
        case MessageWhat.PING_SUCCESS:
        	isPingSuccess = true;
            tv = new TextView(ctx);
            tv.setTextSize(10);
            tv.setText(nm.getPingResult());
            tv.setTextColor(Color.BLACK);
            roamLayout.addView(tv);
//            successTimes++;
            break;
        case MessageWhat.ROAM_SUCCESS:
        	orignMac = pingMac;
        	isRoamSucceed = true;
            tv = new TextView(ctx);
            tv.setTextSize(10);
            tv.setText(nm.getPingResult());
            tv.setTextColor(Color.BLACK);
            roamLayout.addView(tv);
            successTimes++;
            break;
        case MessageWhat.PING_FAILED:
        	isPingSuccess = false;
            s = new StringBuffer();
            s.append("第").append(current).append("次Ping测试失败");
            tv = new TextView(ctx);
            tv.setTextSize(12);
            tv.setText(s);
            tv.setTextColor(Color.BLACK);
            roamLayout.addView(tv);
            break;
        case MessageWhat.ROAM_FAILED:
            s = new StringBuffer();
            s.append("第").append(current).append("次漫游测试失败");
            tv = new TextView(ctx);
            tv.setTextSize(12);
            tv.setText(s);
            tv.setTextColor(Color.BLACK);
            roamLayout.addView(tv);
            break;
        }
        if (current == frequency) {
            s = new StringBuffer();
            s.append("漫游测试次数：").append(roamTimes);
            s.append("; 成功次数：").append(successTimes).append('\n');
            float tempRate = roamTimes==0?0:(float) successTimes / roamTimes * 100;
            s.append("漫游测试成功率：").append(tempRate).append('%');
            tv = new TextView(ctx);
            tv.setTextSize(13);
            tv.setTextColor(Color.BLUE);
            tv.setText(s);
            roamLayout.addView(tv);
            tvTesting.setText("测试完毕");

            task.endTime = StringUtils.getDateTime();
            task.userRoamSuccessRate = String.valueOf(tempRate);

            this.dismissProgressDialog();
            isOver = true;
        //    new UploadResultTask().execute();          /////////////////////////////////////////
        }
        setScrollViewDown(roamSv);
        processing = false;
    }

    private void start() {
    	tvTesting.setText("正在测试...");
    	llPb.setVisibility(View.VISIBLE);
        processing = false;
        current = 0;
        successTimes = 0;
        roamLayout.removeAllViews();
        WifiInfo wifiInfo = wlanManager.getCurrentNetwork();
        if(wifiInfo!=null) {
        	orignMac = wifiInfo.getBSSID();
        	priorMac = wifiInfo.getBSSID();
        }
        final FTPConfig ftp = this.getFTPConfig(ctx);
        if (ftp!=null && ftp.userName!=null && ftp.userName.length() > 0) {
            final String ip = ipEt.getText().toString();
            frequency = StringUtils.parseInt(frequencyEt.getText().toString());
            pb.setMax(frequency);
            final int bytes = StringUtils.parseInt(byteEt.getText().toString());
            if (StringUtils.isIPV4(ip)) {
//                this.showProgressDialog(ctx, "正在进行漫游测试...", frequency);
                initTask(task, ctx, ConnectivityManager.TYPE_WIFI);
                task.startTime = StringUtils.getDateTime();
                new Thread() {
                    public void run() {
                        while (current < frequency) {
                            if (!processing) {
                                processing = true;
                                current++;
                                WifiInfo wifiInfo = wlanManager.getCurrentNetwork();
                                if(wifiInfo!=null) {
                                	currentMac = wifiInfo.getBSSID();
                                	if(currentMac!=null && priorMac!=null && !priorMac.equals(currentMac)) {
                                		priorMac = currentMac;
                                		roamTimes ++;
                                	}
                                }
                                if(currentMac!=null && orignMac!=null && !currentMac.equals(orignMac)){
                                	System.out.println("-----漫游测试  currentMac=" + currentMac + " orignMac=" + orignMac);
                                	if(isRoamSucceed) {
                                		System.out.println("-----漫游测试  无休眠【1】...");
                                		isRoamSucceed = false;
                                		nm.ping(ip, 1, bytes);
                                	} else {
                                    	pingMac = currentMac;
    	                            	 try {
    	                            		 System.out.println("-----漫游测试  休眠 3 秒中...");
    	                                     Thread.sleep(3000);
    	                                 } catch (InterruptedException e) { }
                                    	nm.pingForRoam(ip, 1, bytes);
                                	}
                                	
                                } else {
                                	System.out.println("-----漫游测试  无休眠【2】...");
                                	isRoamSucceed = false;
                                	if(isPingSuccess) {
                                		try {
	   	                                     Thread.sleep(1000);
	   	                                 } catch (InterruptedException e) { }
                                	}
                                    nm.ping(ip, 1, bytes);
								}
                            }
                        }
                    }
                }.start();
        		isOver = false;
            } else {
                this.showMessage(ctx, "请输入正确的IPV4地址!");
            }
        }
    }

    private void scanWifi() {
        this.showMessageDialog(ctx, "正在扫描附近Wifi热点...");
        new Thread() {
            public void run() {
                wlanManager.startScan();
            }
        }.start();

    }

    private void enableNetWork(final ScanResult scan) {
        this.showMessageDialog(ctx, "正在连接Wifi热点...");
        new Thread() {
            public void run() {
                wlanManager.connect(scan);
            }
        }.start();

    }

}
